import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:permission_handler/permission_handler.dart';


import '../net/api/http_api.dart';
import '../net/response/upload_file_response_data.dart';
import '../util/ext_utils.dart';

class UploadFileModel extends BaseMvvmModel {
  @override
  void onCleared() {}

  Future<UploadFileResponseData> uploadFile(String filePath,
      ) async {
    var fileType = filePath.split(".").last;
    var map = {
      "file": await MultipartFile.fromFile(filePath),
      'fileType': fileType,
    };
    var result = await HttpGo.instance
        .postData(HttpApi.uploadFile, data: FormData.fromMap(map));
    if ("0" == result['code']) {
      return UploadFileResponseData.fromJson(result['data']);
    } else {
      throw result['msg'];
    }
  }

  void showSelectCameraWithUpload(
      BuildContext context,
      Function(UploadFileResponseData data) result,{Function()? onStart,
        Function()? onEnd,
        Function(String error)? onError}) {
    var items = ['拍摄', '相册'];
    showBottomSelect(context, items: items, onSelect: (str) async {
      XFile? data;
      if (str == "拍摄") {

        await Permission.camera.checkRequestPermission(context,onSuccess: () async {
          data = await ImagePicker().pickImage(source: ImageSource.camera);
          upload(data: data,result: result,onStart: onStart,onEnd: onEnd,onError: onError);
        },msg: "使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限");
      } else if (str == "相册") {
        var isAndroid13 = await isAndroid13OrAbove();
        if(isAndroid13){
          await Permission.photos.checkRequestPermission(context, onSuccess: () async {
            data = await ImagePicker().pickImage(source: ImageSource.gallery);
            upload(data: data,result: result,onStart: onStart,onEnd: onEnd,onError: onError);
          }, msg: '从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限');
        }else{
          await Permission.storage.checkRequestPermission(context, onSuccess: () async {
            data = await ImagePicker().pickImage(source: ImageSource.gallery);
            upload(data: data,result: result,onStart: onStart,onEnd: onEnd,onError: onError);
          }, msg: '从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限');
        }

      }
      // debugPrint("文件路径====》${data?.path}");

    });
  }

  Future<void> upload({XFile? data,Function(UploadFileResponseData data)? result,Function()? onStart,
    Function()? onEnd,
    Function(String error)? onError}) async {
    if(data!=null){
      if(onStart!=null){
        onStart();
      }
      try{
        var uploadData = await uploadFile(data!.path);
        result?.call(uploadData);
        if(onEnd!=null){
          onEnd();
        }
      }catch(e){
        if(onError!=null){
          onError(NetErrorUtils.getNetError(e));
        }
        if(onEnd!=null){
          onEnd();
        }
      }
    }
  }
}
